package com.education.ai.service.impl;

import com.education.ai.entity.MediaResource;
import com.education.ai.repository.MediaResourceRepository;
import com.education.ai.service.MediaResourceService;
import com.education.ai.service.WanxiangService;
import com.education.ai.util.TeacherContext;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.web.reactive.function.client.WebClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 多媒体资源服务实现类
 */
@Service
@Slf4j
public class MediaResourceServiceImpl implements MediaResourceService {

    @Autowired
    private MediaResourceRepository mediaResourceRepository;

    @Autowired
    @Qualifier("tongYiVisionWebClientCustom")
    private WebClient tongYiVisionWebClient;

    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private WanxiangService wanxiangService;

    @Value("${tongyi.wanxiang.api.key:${TONGYI_WANXIANG_API_KEY:your-api-key-here}}")
    private String apiKey;

    public MediaResourceServiceImpl() {
        // 直接使用API模型，不需要模拟模式
    }

    @Override
    public List<MediaResource> getAllMediaResources() {
        return mediaResourceRepository.findAll();
    }

    @Override
    public MediaResource getMediaResourceById(Long id) {
        return mediaResourceRepository.findById(id).orElse(null);
    }

    @Override
    public List<MediaResource> getMediaResourcesByType(String resourceType) {
        return mediaResourceRepository.findByResourceType(resourceType);
    }

    @Override
    public List<MediaResource> getMediaResourcesBySubject(String subject) {
        return mediaResourceRepository.findBySubject(subject);
    }

    @Override
    public List<MediaResource> getMediaResourcesByGrade(String grade) {
        return mediaResourceRepository.findByGrade(grade);
    }

    @Override
    public MediaResource saveMediaResource(MediaResource mediaResource) {
        // 设置关联教师ID
        String currentTeacherId = TeacherContext.getTeacherId();
        if (currentTeacherId != null && (mediaResource.getTeacherId() == null || mediaResource.getTeacherId().isEmpty())) {
            log.info("为媒体资源关联教师ID: {}", currentTeacherId);
            mediaResource.setTeacherId(currentTeacherId);
        }

        return mediaResourceRepository.save(mediaResource);
    }

    @Override
    public void deleteMediaResource(Long id) {
        mediaResourceRepository.deleteById(id);
    }

    @Override
    public MediaResource generateImage(String subject, String grade, String topic, String description) {
        log.info("开始生成教学图片: 学科={}, 年级={}, 主题={}", subject, grade, topic);

        try {
            // 构建提示词
            String prompt = String.format(
                "为%s年级%s科目的'%s'主题创建一张教学图片。%s",
                grade, subject, topic, description
            );

            // 使用通义万象服务生成图片
            String imageUrl = wanxiangService.generateImage(prompt);
            log.info("成功生成图片URL: {}", imageUrl);

            // 获取当前教师ID
            String currentTeacherId = TeacherContext.getTeacherId();

            // 创建并保存多媒体资源
            MediaResource mediaResource = MediaResource.builder()
                .subject(subject)
                .grade(grade)
                .topic(topic)
                .resourceType("IMAGE")
                .title(topic + "教学图片")
                .description(description)
                .url(imageUrl)
                .format("jpg")
                .createdTime(LocalDateTime.now())
                .build();

            // 设置教师ID
            if (currentTeacherId != null) {
                log.info("为生成的图片关联教师ID: {}", currentTeacherId);
                mediaResource.setTeacherId(currentTeacherId);
            }

            MediaResource savedResource = mediaResourceRepository.save(mediaResource);
            log.info("成功生成教学图片, ID: {}", savedResource.getId());
            return savedResource;

        } catch (Exception e) {
            log.error("生成教学图片时发生错误", e);
            throw new RuntimeException("生成教学图片失败: " + e.getMessage(), e);
        }
    }

    @Override
    public MediaResource generateVideo(String subject, String grade, String topic, String description, Integer duration) {
        log.info("开始生成教学视频: 学科={}, 年级={}, 主题={}, 时长={}秒", subject, grade, topic, duration);
        
        // 调用带teacherId参数的方法，并从当前上下文获取教师ID
        return generateVideo(subject, grade, topic, description, duration, TeacherContext.getTeacherId());
    }
    
    @Override
    public MediaResource generateVideo(String subject, String grade, String topic, String description, Integer duration, String teacherId) {
        log.info("开始生成教学视频: 学科={}, 年级={}, 主题={}, 时长={}秒, 教师ID={}", subject, grade, topic, duration, teacherId);

        try {
            // 构建提示词
            String prompt = String.format(
                "为%s年级%s科目的'%s'主题创建一个教学视频。%s",
                grade, subject, topic, description
            );

            // 使用通义万象服务生成视频
            String videoUrl = wanxiangService.generateVideo(prompt, duration);
            log.info("成功生成视频URL: {}", videoUrl);

            MediaResource mediaResource = MediaResource.builder()
                .subject(subject)
                .grade(grade)
                .topic(topic)
                .resourceType("VIDEO")
                .title(topic + "教学视频")
                .description(description)
                .url(videoUrl)
                .duration(duration)
                .format("mp4")
                .createdTime(LocalDateTime.now())
                .build();

            // 设置教师ID
            if (teacherId != null && !teacherId.isEmpty()) {
                log.info("为生成的视频关联教师ID: {}", teacherId);
                mediaResource.setTeacherId(teacherId);
            }

            MediaResource savedResource = mediaResourceRepository.save(mediaResource);
            log.info("成功生成教学视频, ID: {}", savedResource.getId());
            return savedResource;

        } catch (Exception e) {
            log.error("生成教学视频时发生错误", e);
            throw new RuntimeException("生成教学视频失败: " + e.getMessage(), e);
        }
    }

    @Override
    public MediaResource generateImageWithWanxiang(String subject, String grade, String topic, String description, int imageCount, String size, String teacherId) {
        log.info("开始使用通义万象模型生成教学图片: 学科={}, 年级={}, 主题={}, 描述={}, 图片数量={}, 尺寸={}, 教师ID={}",
                subject, grade, topic, description, imageCount, size, teacherId);

        try {
            // 检查参数
            if (subject == null || subject.trim().isEmpty()) {
                throw new IllegalArgumentException("学科不能为空");
            }

            if (grade == null || grade.trim().isEmpty()) {
                throw new IllegalArgumentException("年级不能为空");
            }

            if (topic == null || topic.trim().isEmpty()) {
                throw new IllegalArgumentException("主题不能为空");
            }

            if (description == null) {
                description = ""; // 使用空字符串代替null
            }

            if (imageCount <= 0) {
                imageCount = 1;
            }

            // 验证并修正size格式
            if (size == null || size.trim().isEmpty() || !size.contains("*")) {
                log.warn("Size格式错误或为空，使用默认值: 1024*1024");
                size = "1024*1024";
            }

            // 检查API密钥是否配置
            if (apiKey == null || apiKey.equals("your-api-key-here")) {
                log.error("API密钥未配置，请在application.properties中设置tongyi.vision.api.key");
                throw new RuntimeException("API密钥未正确配置");
            }

            // 构建完整提示词
            String prompt = String.format(
                "为%s年级%s科目的'%s'主题创建一张教学图片。%s",
                grade, subject, topic, description
            );

            log.debug("生成的prompt: {}", prompt);

            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            // 使用通义万象2.1版本的文生图模型
            requestBody.put("model", "wanx2.1-t2i-turbo");

            Map<String, Object> input = new HashMap<>();
            input.put("prompt", prompt);
            requestBody.put("input", input);

            Map<String, Object> parameters = new HashMap<>();
            parameters.put("size", size);
            parameters.put("n", imageCount);
            parameters.put("prompt_extend", true);
            parameters.put("watermark", false);
            requestBody.put("parameters", parameters);

            log.debug("请求体: {}", requestBody);

            // 创建HTTP头部
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + apiKey);
            headers.set("X-DashScope-Async", "enable");

            // 创建HTTP请求实体
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);

            // 使用RestTemplate发送请求
            RestTemplate restTemplate = new RestTemplate();
            log.info("发送请求到通义万象API...");
            ResponseEntity<Map> createTaskResponse = restTemplate.exchange(
                "https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis",
                HttpMethod.POST,
                requestEntity,
                Map.class
            );

            log.debug("API响应状态: {}", createTaskResponse.getStatusCode());

            // 检查响应状态
            if (!createTaskResponse.getStatusCode().is2xxSuccessful()) {
                log.error("API响应不成功: {}", createTaskResponse.getBody());
                throw new RuntimeException("创建通义万象图片生成任务失败, HTTP状态码: " + createTaskResponse.getStatusCodeValue());
            }

            // 获取任务ID
            Map<String, Object> responseBody = createTaskResponse.getBody();
            log.debug("响应体: {}", responseBody);

            if (responseBody == null || !responseBody.containsKey("output")) {
                log.error("API响应格式错误，缺少output字段: {}", responseBody);
                throw new RuntimeException("API响应格式错误");
            }

            Map<String, Object> outputMap = (Map<String, Object>) responseBody.get("output");
            String taskId = (String) outputMap.get("task_id");
            String taskStatus = (String) outputMap.get("task_status");

            if (taskId == null || taskId.isEmpty()) {
                log.error("未能获取任务ID: {}", outputMap);
                throw new RuntimeException("API响应中未包含任务ID");
            }

            log.info("成功创建通义万象图片生成任务, 任务ID: {}, 状态: {}", taskId, taskStatus);

            // 等待任务完成并获取结果
            String imageUrl = waitForTaskCompletion(taskId, restTemplate, headers);

            if (imageUrl == null || imageUrl.isEmpty()) {
                throw new RuntimeException("通义万象图片生成失败，未能获取图片URL");
            }

            log.info("成功获取生成的图片URL: {}", imageUrl);

            // 创建并保存多媒体资源
            MediaResource mediaResource = MediaResource.builder()
                .subject(subject)
                .grade(grade)
                .topic(topic)
                .resourceType("IMAGE")
                .title(topic + "教学图片")
                .description(description)
                .url(imageUrl)
                .format("jpg")
                .createdTime(LocalDateTime.now())
                .build();
                
            // 设置教师ID
            if (teacherId != null && !teacherId.isEmpty()) {
                log.info("为生成的图片设置教师ID: {}", teacherId);
                mediaResource.setTeacherId(teacherId);
            } else {
                // 尝试从上下文获取当前登录的教师ID
                String currentTeacherId = TeacherContext.getTeacherId();
                if (currentTeacherId != null && !currentTeacherId.isEmpty()) {
                    log.info("从上下文获取并设置教师ID: {}", currentTeacherId);
                    mediaResource.setTeacherId(currentTeacherId);
                }
            }

            MediaResource savedResource = mediaResourceRepository.save(mediaResource);
            log.info("成功保存教学图片资源, ID: {}", savedResource.getId());
            return savedResource;

        } catch (Exception e) {
            log.error("使用通义万象生成教学图片时发生错误", e);
            throw new RuntimeException("使用通义万象生成教学图片失败: " + e.getMessage(), e);
        }
    }

    // 等待异步任务完成并获取图片URL
    private String waitForTaskCompletion(String taskId, RestTemplate restTemplate, HttpHeaders headers) {
        // 最大重试次数
        final int MAX_RETRIES = 30;
        // 每次重试间隔时间(毫秒)
        final long RETRY_INTERVAL = 2000;

        for (int i = 0; i < MAX_RETRIES; i++) {
            try {
                // 等待一定时间后查询结果
                Thread.sleep(RETRY_INTERVAL);

                // 发送查询请求
                HttpEntity<String> requestEntity = new HttpEntity<>(headers);
                ResponseEntity<Map> checkTaskResponse = restTemplate.exchange(
                    "https://dashscope.aliyuncs.com/api/v1/tasks/" + taskId,
                    HttpMethod.GET,
                    requestEntity,
                    Map.class
                );

                // 检查任务状态
                Map<String, Object> output = (Map<String, Object>) checkTaskResponse.getBody().get("output");
                String taskStatus = (String) output.get("task_status");

                log.info("查询任务状态: {}, 任务ID: {}", taskStatus, taskId);

                if ("FAILED".equals(taskStatus)) {
                    log.error("通义万象图片生成任务失败, 任务ID: {}", taskId);
                    break;
                } else if ("SUCCEEDED".equals(taskStatus)) {
                    // 任务成功，获取图片URL
                    List<Map<String, Object>> results = (List<Map<String, Object>>) output.get("results");
                    if (results != null && !results.isEmpty()) {
                        String imageUrl = (String) results.get(0).get("url");
                        return imageUrl;
                    }
                    break;
                }
                // 任务仍在处理中，继续等待

            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                throw new RuntimeException("等待图片生成任务被中断", e);
            } catch (Exception e) {
                log.error("查询图片生成任务状态时出错", e);
            }
        }

        // 超过最大重试次数仍未成功
        log.error("通义万象图片生成任务超时, 任务ID: {}", taskId);
        return null;
    }

    @Override
    public Page<MediaResource> getMediaResourcesByTeacherId(String teacherId, Pageable pageable) {
        log.info("分页查询教师ID={}的多媒体资源，页码={}，每页大小={}", 
                 teacherId, pageable.getPageNumber(), pageable.getPageSize());
        
        return mediaResourceRepository.findByTeacherId(teacherId, pageable);
    }
} 